package com.su.dolphin.view.activity;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.su.dolphin.R;
import com.su.dolphin.common.interfaces.IUITemplete;
import com.su.dolphin.core.notification.DpMessageCenter;
import com.su.dolphin.core.notification.DpMessageCenter.INotify;
import com.su.dolphin.core.notification.DpMessageCenter.MCMessage;
import com.su.dolphin.utils.LogUtil;
import com.su.dolphin.utils.ViewUtil;
import com.su.dolphin.utils.mgr.DpActivityManager;
import com.su.dolphin.utils.ui.DpTitleBar;

public abstract class BaseActivity extends FragmentActivity implements INotify,
        IUITemplete, OnClickListener {

    private boolean isDestroied;
    private FrameLayout mRootView;
    private boolean enableTitleBar = true;
    private int TITLEBAR_HEIGHT = ViewUtil.dip2px(48);

    // 显示InputMethod
    private static final int HANDLER_SHOW_INPUT_METHOD = 3;

    private Handler mBaseUIHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {

                case HANDLER_SHOW_INPUT_METHOD: {
                    try {
                        InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        im.showSoftInput((View) msg.obj, 0);
                    } catch (Exception e) {
                    }
                }
                break;
            }
        }

        ;
    };
    private DpTitleBar mDpTitleBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        DpActivityManager.i().addActivity(this);
        super.onCreate(savedInstanceState);
        // //注意支持api 11以上!
        // if (getActionBar() != null) {
        // getActionBar().setDisplayHomeAsUpEnabled(true);
        // }
    }

    protected void register(int messageId) {
        DpMessageCenter.i().register(this, messageId);
    }

    /**
     * @param enable
     * @title: setTitlebarEnable
     * @description: 是否使用DpTitlebar, 默认使用, 禁用请在setContentView之前设置!
     * @return: void
     */
    public void setTitlebarEnable(boolean enable) {
        enableTitleBar = enable;
    }

    @Override
    public void setTitle(CharSequence title) {
        if (mDpTitleBar != null) {
            mDpTitleBar.setTitle(title);
        }
    }

    @Override
    public void setContentView(int layoutResID) {
        setContentView(getLayoutInflater().inflate(layoutResID, null));
    }

    @Override
    public void setContentView(View view) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        setContentView(view, params);
    }

    @Override
    public void setContentView(View view, LayoutParams params) {
        // 所有的Activity 其实都是一个 base的layout 我们可以在base上添加各种全局图层!
        mRootView = (FrameLayout) getLayoutInflater().inflate(
                R.layout.activity_base, null);
        FrameLayout.LayoutParams paramsContent = new FrameLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        if (enableTitleBar) {
            initDpTitleBar();
            paramsContent.topMargin = TITLEBAR_HEIGHT;
        }
        mRootView.addView(view, paramsContent);
        super.setContentView(mRootView, params);
        initView();
        setListener();
        initData();
    }

    public DpTitleBar getDpTitleBar() {
        if (mDpTitleBar == null) {
            if (enableTitleBar) {
                initDpTitleBar();
            } else {
                throw new RuntimeException("have you disabled your titlebar ?");
            }
        }
        return mDpTitleBar;
    }

    private void initDpTitleBar() {
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                TITLEBAR_HEIGHT);
        mDpTitleBar = new DpTitleBar(this);
        mRootView.addView(mDpTitleBar, params);
    }

    /**
     * 关闭软键盘
     */
    public void hideKeyboard() {
        try {
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mRootView.getWindowToken(), 0);
        } catch (Exception e) {
        }
    }

    // =============== Key Event Start =====================

    @Override
    public final boolean onKeyDown(int keyCode, KeyEvent event) {

        // 子类如果实现拦截onKeydown则，先执行子类的onkeydonw
        if (onKeyDownPrepared(keyCode, event)) {
            return true;
        }
        if (event.getAction() == KeyEvent.ACTION_DOWN
                && event.getRepeatCount() == 0) {
            LogUtil.i("onKeyDown keyCode=" + keyCode);

            if (onKeyDownFinish(keyCode, event)) {
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * onKeyDonw执行结束调用，也就是onkeydonw调用页面关闭前调用
     */
    public boolean onKeyDownFinish(int keyCode, KeyEvent event) {
        return false;
    }

    /**
     * onKeyDonw执行前拦截
     */
    public boolean onKeyDownPrepared(int keyCode, KeyEvent event) {
        return false;
    }

    // =============== Key Event End =====================

    @Override
    protected void onResume() {
        isDestroied = false;
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        isDestroied = true;
        super.onStop();
    }

    /**
     * 真正通知子Activity相关消息, onNotify 只由baseactivity 接收
     */
    public void onNotify(MCMessage notification) {
    }

    ;

    /**
     * 子类函数禁止调用这个函数, 这个函数是用来和MC交互使用的. isDestroied是为了防止在Activity销毁之后任何可以收到通知
     */
    @Override
    public final void onNotifyInner(MCMessage notification) {
        if (!isDestroied) {
            onNotify(notification);
        }
    }

    // @Override
    // public boolean onOptionsItemSelected(android.view.MenuItem item) {
    // switch (item.getItemId()) {
    // case android.R.id.home:
    // finish();
    // return true;
    // }
    // return super.onOptionsItemSelected(item);
    // }

    protected void initFragments() {
    }

    ;

    @Override
    public void onClick(View arg0) {

    }

    /**
     * 显示对话框
     *
     * @param dialog
     * @title: showDialog
     * @description: TODO
     * @return: void
     */
    public void showDialog(Dialog dialog) {
        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
    }

    /**
     * 关闭对话框
     *
     * @param progressDialog
     */
    public void dismissDialog(Dialog dialog) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}
